import axios from 'axios'
import { baseURL } from '@/all/instant'
import router from "@/router";
import Vue from 'vue'
import {
  Loading
} from 'element-ui';
import { RequestTimeout as timeout } from '../all/instant.js'

// 设置请求基本参数
const request = axios.create({
  headers:{
    'Content-Type':'application/json',
    // 'Content-Type':'application/x-www-form-urlencoded',
  },
  baseURL,
  timeout
})


// 请求前对请求的操作
request.interceptors.request.use(config => {
  // 全局使用请求样式
  Vue.prototype.globalLoading = Loading.service({
    lock: true,
    text: '加载中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.5)'
  });

  if(config.method === 'post'){
    if(config.url === 'api/user/login'){
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
  }
  
  // 请求之前看是否存在token，存在的话我们就带着token请求数据
  // if(userStore.state.token) config.headers['AuthorizationJwt'] ='Bearer '+ userStore.state.token
  const token = JSON.parse(localStorage.getItem('vuex'))?.user?.token || ''
  if(token) config.headers['AuthorizationJwt'] = token
  return config
},err => {
   Vue.prototype.$message("请求服务器失败")
  return err
})

// 请求后在返回之前做出相应操作
request.interceptors.response.use(response => {
  Vue.prototype.globalLoading.close()
  response.data.code === 200?Vue.prototype.$message(response.data.msg,"success") : ""
  return response.data
},err => {
  Vue.prototype.globalLoading.close()
  if(err.response.status === 401) {
    Vue.prototype.$message(err.response.data.msg + ",请先进行登录")
    router.push('/login')
  }
  else Vue.prototype.$message("服务器响应失败")
  return err
})

export default request